import {Component, OnInit, ViewEncapsulation, ViewChild, OnDestroy} from '@angular/core';
import {ToolsService} from "@shared/service/tools/tools.service";
import {ActivatedRoute, Router} from "@angular/router";

import {AuthService} from "@shared/service/auth/auth.service";
import {CommunityService} from "../community.service";
import {Subject} from "rxjs/Rx";
import {Subscription} from "rxjs/Subscription";

import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {SocialCircle} from "@interface/index";



@Component({
  selector: 'my-circle',
  templateUrl: './my-circle.component.html',
  styleUrls: ['./my-circle.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class MyCircleComponent implements OnInit , OnDestroy {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public subscription: Subscription = new Subscription();
  public circleList: Array<SocialCircle> = [];
  public myCreateCircles: Array<SocialCircle> = [];
  public params = {
    page: 1,
    rows: 10
  };
  public userId;

  constructor(public router: Router,
              public communityService: CommunityService,
              private route: ActivatedRoute,
              public toolsService: ToolsService,
              private auth: AuthService) {

    this.getMyCreateCircle(this.params);
    this.getCirclesJoin();
    this.userId = this.auth.getUserId();
  }

  /**
   * @description 获取我加入的圈子列表
   * @author zhupw1360
   * @date 2017-12-11
   */
  getCirclesJoin() {
    this.communityService.getCirclesJoin(this.params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.params.page++;
        this.infiniteScroll.complete();
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
        const circles = res.data.list;
        for (let i = 0; i < circles.length; i++) {
          if (circles[i].createUserId === this.userId) {
            Object.assign(circles[i], {
              selfCircle: true
            });
          }
        }
        this.circleList = [...this.circleList, ...circles];
      }
    });
  }

  /**
   * @description 获取我创建的圈子列表（2.3.0版本只有一个）
   * @author zhupw1360
   * @date 2017-12-11
   */
  getMyCreateCircle(params) {
    this.communityService.getMyCreateCircle(params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.myCreateCircles = [...this.myCreateCircles, ...res.data.list];
      }
    });
  }

  // 跳转圈子详情
  goToCirclesDetail(circleId: number) {
    this.router.navigate([`/community/circle`, circleId]);
  }


  ngOnInit() {

  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
